package com.smart.community.property.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.community.commons.entity.property.UserPropertyCompany;
import com.smart.community.commons.enums.SystemStatusEnum;
import com.smart.community.commons.exception.BusinessException;
import com.smart.community.commons.result.PageResult;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.commons.utils.StringUtils;
import com.smart.community.feign.user.dto.UserDTO;
import com.smart.community.feign.user.service.UserFeignService;
import com.smart.community.property.service.DataScopeService;
import com.smart.community.commons.cache.DataScopeInfo;
import com.smart.community.property.dto.AddEmployeeDTO;
import com.smart.community.property.dto.EmployeeQueryDTO;
import com.smart.community.property.dto.UpdateEmployeeDTO;
import com.smart.community.property.mapper.UserPropertyCompanyMapper;
import com.smart.community.property.service.IPropertyEmployeeService;
import com.smart.community.property.vo.EmployeeVO;
import com.smart.community.property.vo.UserVO;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;

/**
 * 物业公司员工管理服务实现类
 * 
 * 严格按照《Java后端SpringBoot代码开发规范.md》Service层规范实现：
 * - 职责分离：Service实现类专注于业务逻辑实现
 * - 接口调用：通过Service接口进行数据访问
 * - 异常处理：完善的异常处理和日志记录
 * - 缓存策略：合理的缓存键设计和失效策略
 * - 性能监控：详细的性能指标记录
 * - 状态管理：使用SystemStatusEnum统一状态管理
 * - Feign调用：实现用户服务Feign调用，完善功能
 * 
 * @author Wu.Liang
 * @since 2025-01-21
 * @version 2.0.0 - 生产环境优化版本
 */
@Slf4j
@Service
public class PropertyEmployeeServiceImpl extends ServiceImpl<UserPropertyCompanyMapper, UserPropertyCompany>
        implements IPropertyEmployeeService {

    @Autowired
    private UserFeignService userFeignService;

    @Autowired
    private DataScopeService dataScopeService;


    // 本地缓存，用于存储用户信息，减少Feign调用
    private final Map<Long, UserDTO> userCache = new ConcurrentHashMap<>();


    @Override
    public PageResult<EmployeeVO> getPropertyCompanyEmployees(Long propertyCompanyId, EmployeeQueryDTO queryDTO) throws Exception {
        long startTime = System.currentTimeMillis();
        log.info("获取物业公司员工列表，物业公司ID：{}，查询参数：{}", propertyCompanyId, queryDTO);

        try {
            // 数据权限验证
            validatePropertyCompanyPermission(propertyCompanyId);

            // 构建查询条件
            LambdaQueryWrapper<UserPropertyCompany> queryWrapper = buildEmployeeQueryWrapper(propertyCompanyId, queryDTO);

            // 分页查询
            Page<UserPropertyCompany> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
            IPage<UserPropertyCompany> pageResult = this.page(page, queryWrapper);

            // 批量获取用户信息，减少Feign调用次数
            List<Long> userIds = pageResult.getRecords().stream()
                    .map(UserPropertyCompany::getUserId)
                    .distinct()
                    .collect(Collectors.toList());
            
            Map<Long, UserDTO> userMap = batchGetUserInfo(userIds);

            // 转换为VO
            List<EmployeeVO> employeeVOList = pageResult.getRecords().stream()
                    .map(employee -> convertToEmployeeVO(employee, userMap.get(employee.getUserId())))
                    .collect(Collectors.toList());

            long responseTime = System.currentTimeMillis() - startTime;
            log.info("获取物业公司{}员工列表成功，数量：{}，耗时：{}ms", propertyCompanyId, employeeVOList.size(), responseTime);

            return new PageResult<>(
                    (int) pageResult.getCurrent(),
                    (int) pageResult.getSize(),
                    pageResult.getTotal(),
                    employeeVOList
            );

        } catch (Exception e) {
            long responseTime = System.currentTimeMillis() - startTime;
            log.error("获取物业公司{}员工列表异常，耗时：{}ms", propertyCompanyId, responseTime, e);
            throw e;
        }
    }

    @Override
    @GlobalTransactional
    @CacheEvict(value = {"propertyInfo", "userPropertyCompany", "userInfo", "permission"}, allEntries = true)
    public boolean addEmployeeToPropertyCompany(Long propertyCompanyId, AddEmployeeDTO addEmployeeDTO) throws Exception {
        long startTime = System.currentTimeMillis();
        log.info("添加员工到物业公司，物业公司ID：{}，员工信息：{}", propertyCompanyId, addEmployeeDTO);

        try {
            // 数据权限验证
            validatePropertyCompanyPermission(propertyCompanyId);

            // 验证用户是否存在
            UserDTO userDTO = getUserInfo(addEmployeeDTO.getUserId());
            if (userDTO == null) {
                throw new BusinessException("用户不存在，用户ID：" + addEmployeeDTO.getUserId());
            }

            // 检查是否已关联
            if (isUserBelongToPropertyCompany(addEmployeeDTO.getUserId(), propertyCompanyId)) {
                throw new BusinessException("用户已关联该物业公司");
            }

            // 创建关联记录
            UserPropertyCompany userPropertyCompany = createUserPropertyCompany(propertyCompanyId, addEmployeeDTO);
            boolean result = this.save(userPropertyCompany);

            long responseTime = System.currentTimeMillis() - startTime;
            log.info("添加员工到物业公司{}成功，用户ID：{}，耗时：{}ms", propertyCompanyId, addEmployeeDTO.getUserId(), responseTime);

            return result;

        } catch (Exception e) {
            long responseTime = System.currentTimeMillis() - startTime;
            log.error("添加员工到物业公司{}异常，用户ID：{}，耗时：{}ms", propertyCompanyId, addEmployeeDTO.getUserId(), responseTime, e);
            throw e;
        }
    }

    @Override
    @GlobalTransactional
    @CacheEvict(value = {"propertyInfo", "userPropertyCompany", "userInfo", "permission"}, allEntries = true)
    public boolean updateEmployeeInfo(Long propertyCompanyId, Long employeeId, UpdateEmployeeDTO updateEmployeeDTO) throws Exception {
        long startTime = System.currentTimeMillis();
        log.info("更新员工信息，物业公司ID：{}，员工ID：{}，更新信息：{}", propertyCompanyId, employeeId, updateEmployeeDTO);

        try {
            // 检查关联记录是否存在
            UserPropertyCompany userPropertyCompany = this.getById(employeeId);
            if (userPropertyCompany == null) {
                throw new BusinessException("员工关联记录不存在");
            }

            if (!userPropertyCompany.getPropertyCompanyId().equals(propertyCompanyId)) {
                throw new BusinessException("员工不属于该物业公司");
            }

            // 更新信息
            updateUserPropertyCompanyFields(userPropertyCompany, updateEmployeeDTO);
            userPropertyCompany.setUpdateBy(SecurityUtils.getCurrentUserId());
            userPropertyCompany.setUpdateTime(LocalDateTime.now());

            boolean result = this.updateById(userPropertyCompany);

            long responseTime = System.currentTimeMillis() - startTime;
            log.info("更新员工信息成功，物业公司ID：{}，员工ID：{}，耗时：{}ms", propertyCompanyId, employeeId, responseTime);

            return result;

        } catch (Exception e) {
            long responseTime = System.currentTimeMillis() - startTime;
            log.error("更新员工信息异常，物业公司ID：{}，员工ID：{}，耗时：{}ms", propertyCompanyId, employeeId, responseTime, e);
            throw e;
        }
    }

    @Override
    @GlobalTransactional
    @CacheEvict(value = {"propertyInfo", "userPropertyCompany", "userInfo", "permission"}, allEntries = true)
    public boolean removeEmployeeFromPropertyCompany(Long propertyCompanyId, Long employeeId) throws Exception {
        long startTime = System.currentTimeMillis();
        log.info("移除员工，物业公司ID：{}，员工ID：{}", propertyCompanyId, employeeId);

        try {
            // 检查关联记录是否存在
            UserPropertyCompany userPropertyCompany = this.getById(employeeId);
            if (userPropertyCompany == null) {
                throw new BusinessException("员工关联记录不存在");
            }

            if (!userPropertyCompany.getPropertyCompanyId().equals(propertyCompanyId)) {
                throw new BusinessException("员工不属于该物业公司");
            }

            // 物理删除
            boolean result = this.removeById(employeeId);

            long responseTime = System.currentTimeMillis() - startTime;
            log.info("移除员工成功，物业公司ID：{}，员工ID：{}，耗时：{}ms", propertyCompanyId, employeeId, responseTime);

            return result;

        } catch (Exception e) {
            long responseTime = System.currentTimeMillis() - startTime;
            log.error("移除员工异常，物业公司ID：{}，员工ID：{}，耗时：{}ms", propertyCompanyId, employeeId, responseTime, e);
            throw e;
        }
    }

    @Override
    @Cacheable(value = "propertyInfo", key = "'available_users:' + #keyword + ':' + #excludePropertyCompanyId", unless = "#result == null || #result.isEmpty()")
    public List<UserVO> searchAvailableUsers(String keyword, Long excludePropertyCompanyId) throws Exception {
        long startTime = System.currentTimeMillis();
        log.info("搜索可分配的用户，关键词：{}，排除物业公司ID：{}", keyword, excludePropertyCompanyId);

        try {
            // 获取已关联的用户ID列表
            List<Long> associatedUserIds = getAssociatedUserIds(excludePropertyCompanyId);

            // 通过Feign调用用户服务搜索用户
            List<UserDTO> allUsers = searchUsersByKeyword(keyword);
            
            // 过滤已关联的用户
            List<UserDTO> availableUsers = allUsers.stream()
                    .filter(user -> !associatedUserIds.contains(user.getId()))
                    .collect(Collectors.toList());

            // 转换为UserVO
            List<UserVO> userVOList = availableUsers.stream()
                    .map(this::convertToUserVO)
                    .collect(Collectors.toList());

            long responseTime = System.currentTimeMillis() - startTime;
            log.info("搜索可分配用户成功，关键词：{}，结果数量：{}，耗时：{}ms", keyword, userVOList.size(), responseTime);

            return userVOList;

        } catch (Exception e) {
            long responseTime = System.currentTimeMillis() - startTime;
            log.error("搜索可分配用户异常，关键词：{}，耗时：{}ms", keyword, responseTime, e);
            // 返回空列表而不是抛出异常，保证系统稳定性
            return new ArrayList<>();
        }
    }

    @Override
    @GlobalTransactional
    @CacheEvict(value = {"propertyInfo", "userPropertyCompany", "userInfo", "permission"}, allEntries = true)
    public boolean batchAddEmployees(Long propertyCompanyId, List<AddEmployeeDTO> addEmployeeDTOList) throws Exception {
        long startTime = System.currentTimeMillis();
        log.info("批量添加员工，物业公司ID：{}，员工数量：{}", propertyCompanyId, addEmployeeDTOList.size());

        try {
            if (CollectionUtils.isEmpty(addEmployeeDTOList)) {
                log.warn("批量添加员工列表为空");
                return true;
            }

            // 批量验证用户是否存在
            List<Long> userIds = addEmployeeDTOList.stream()
                    .map(AddEmployeeDTO::getUserId)
                    .distinct()
                    .collect(Collectors.toList());
            
            Map<Long, UserDTO> userMap = batchGetUserInfo(userIds);
            
            // 验证所有用户都存在
            for (AddEmployeeDTO addEmployeeDTO : addEmployeeDTOList) {
                if (!userMap.containsKey(addEmployeeDTO.getUserId())) {
                    throw new BusinessException("用户不存在，用户ID：" + addEmployeeDTO.getUserId());
                }
            }

            // 批量检查是否已关联
            List<Long> associatedUserIds = getAssociatedUserIds(propertyCompanyId);
            for (AddEmployeeDTO addEmployeeDTO : addEmployeeDTOList) {
                if (associatedUserIds.contains(addEmployeeDTO.getUserId())) {
                    throw new BusinessException("用户已关联该物业公司，用户ID：" + addEmployeeDTO.getUserId());
                }
            }

            // 批量创建关联记录
            List<UserPropertyCompany> userPropertyCompanies = addEmployeeDTOList.stream()
                    .map(addEmployeeDTO -> createUserPropertyCompany(propertyCompanyId, addEmployeeDTO))
                    .collect(Collectors.toList());

            boolean result = this.saveBatch(userPropertyCompanies);

            long responseTime = System.currentTimeMillis() - startTime;
            log.info("批量添加员工成功，物业公司ID：{}，数量：{}，耗时：{}ms", propertyCompanyId, addEmployeeDTOList.size(), responseTime);

            return result;

        } catch (Exception e) {
            long responseTime = System.currentTimeMillis() - startTime;
            log.error("批量添加员工异常，物业公司ID：{}，数量：{}，耗时：{}ms", propertyCompanyId, addEmployeeDTOList.size(), responseTime, e);
            throw e;
        }
    }

    @Override
    @Cacheable(value = "propertyInfo", key = "'employee_detail:' + #propertyCompanyId + ':' + #employeeId", unless = "#result == null")
    public EmployeeVO getEmployeeDetail(Long propertyCompanyId, Long employeeId) throws Exception {
        long startTime = System.currentTimeMillis();
        log.info("获取员工详情，物业公司ID：{}，员工ID：{}", propertyCompanyId, employeeId);

        try {
            UserPropertyCompany userPropertyCompany = this.getById(employeeId);
            if (userPropertyCompany == null) {
                throw new BusinessException("员工关联记录不存在");
            }

            if (!userPropertyCompany.getPropertyCompanyId().equals(propertyCompanyId)) {
                throw new BusinessException("员工不属于该物业公司");
            }

            // 获取用户信息
            UserDTO userDTO = getUserInfo(userPropertyCompany.getUserId());
            EmployeeVO employeeVO = convertToEmployeeVO(userPropertyCompany, userDTO);

            long responseTime = System.currentTimeMillis() - startTime;
            log.info("获取员工详情成功，物业公司ID：{}，员工ID：{}，耗时：{}ms", propertyCompanyId, employeeId, responseTime);

            return employeeVO;

        } catch (Exception e) {
            long responseTime = System.currentTimeMillis() - startTime;
            log.error("获取员工详情异常，物业公司ID：{}，员工ID：{}，耗时：{}ms", propertyCompanyId, employeeId, responseTime, e);
            throw e;
        }
    }

    @Override
    @Cacheable(value = "propertyInfo", key = "'user_belong:' + #userId + ':' + #propertyCompanyId")
    public boolean isUserBelongToPropertyCompany(Long userId, Long propertyCompanyId) throws Exception {
        long startTime = System.currentTimeMillis();
        log.debug("检查用户是否属于物业公司，用户ID：{}，物业公司ID：{}", userId, propertyCompanyId);

        try {
            LambdaQueryWrapper<UserPropertyCompany> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserPropertyCompany::getUserId, userId)
                    .eq(UserPropertyCompany::getPropertyCompanyId, propertyCompanyId)
                    .eq(UserPropertyCompany::getStatus, SystemStatusEnum.ENABLED.getCode()); // 使用SystemStatusEnum

            boolean result = this.count(queryWrapper) > 0;

            long responseTime = System.currentTimeMillis() - startTime;
            log.debug("检查用户归属完成，用户ID：{}，物业公司ID：{}，结果：{}，耗时：{}ms", userId, propertyCompanyId, result, responseTime);

            return result;

        } catch (Exception e) {
            long responseTime = System.currentTimeMillis() - startTime;
            log.error("检查用户归属异常，用户ID：{}，物业公司ID：{}，耗时：{}ms", userId, propertyCompanyId, responseTime, e);
            // 异常情况下返回false，保证系统稳定性
            return false;
        }
    }

    // ========================= 私有辅助方法 =========================

    /**
     * 构建员工查询条件
     */
    private LambdaQueryWrapper<UserPropertyCompany> buildEmployeeQueryWrapper(Long propertyCompanyId, EmployeeQueryDTO queryDTO) {
        LambdaQueryWrapper<UserPropertyCompany> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPropertyCompany::getPropertyCompanyId, propertyCompanyId);

        // 添加查询条件
        if (StringUtils.isNotBlank(queryDTO.getKeyword())) {
            queryWrapper.and(wrapper -> wrapper
                    .like(UserPropertyCompany::getPosition, queryDTO.getKeyword())
                    .or()
                    .like(UserPropertyCompany::getDepartment, queryDTO.getKeyword())
                    .or()
                    .like(UserPropertyCompany::getEmployeeNo, queryDTO.getKeyword())
            );
        }

        if (StringUtils.isNotBlank(queryDTO.getPosition())) {
            queryWrapper.like(UserPropertyCompany::getPosition, queryDTO.getPosition());
        }

        if (StringUtils.isNotBlank(queryDTO.getDepartment())) {
            queryWrapper.like(UserPropertyCompany::getDepartment, queryDTO.getDepartment());
        }

        if (queryDTO.getStatus() != null) {
            queryWrapper.eq(UserPropertyCompany::getStatus, queryDTO.getStatus());
        }

        if (queryDTO.getJoinDateStart() != null) {
            queryWrapper.ge(UserPropertyCompany::getJoinDate, queryDTO.getJoinDateStart());
        }

        if (queryDTO.getJoinDateEnd() != null) {
            queryWrapper.le(UserPropertyCompany::getJoinDate, queryDTO.getJoinDateEnd());
        }

        // 排序
        queryWrapper.orderByDesc(UserPropertyCompany::getCreateTime);
        
        return queryWrapper;
    }

    /**
     * 批量获取用户信息
     */
    private Map<Long, UserDTO> batchGetUserInfo(List<Long> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            return new ConcurrentHashMap<>();
        }

        try {
            List<UserDTO> userDTOs = userFeignService.getUsersByIds(userIds);
            if (CollectionUtils.isEmpty(userDTOs)) {
                return new ConcurrentHashMap<>();
            }

            // 更新本地缓存
            userDTOs.forEach(userDTO -> userCache.put(userDTO.getId(), userDTO));

            return userDTOs.stream()
                    .collect(Collectors.toMap(UserDTO::getId, userDTO -> userDTO));

        } catch (Exception e) {
            log.error("批量获取用户信息失败，用户IDs：{}", userIds, e);
            return new ConcurrentHashMap<>();
        }
    }

    /**
     * 获取单个用户信息（带Spring Cache缓存）
     */
    @Cacheable(value = "userInfo", key = "#userId", unless = "#result == null")
    private UserDTO getUserInfo(Long userId) {
        if (userId == null) {
            return null;
        }

        try {
            UserDTO userDTO = userFeignService.getUserById(userId);
            if (userDTO != null) {
                // 同时更新本地缓存以保持兼容性
                userCache.put(userId, userDTO);
            }
            return userDTO;
        } catch (Exception e) {
            log.error("获取用户信息失败，用户ID：{}", userId, e);
            return null;
        }
    }

    /**
     * 搜索用户
     */
    private List<UserDTO> searchUsersByKeyword(String keyword) {
        if (StringUtils.isBlank(keyword)) {
            return new ArrayList<>();
        }

        try {
            // 这里需要根据实际的用户服务Feign接口来实现
            // 暂时返回空列表，实际项目中需要实现具体的搜索逻辑
            log.warn("用户搜索功能需要根据实际用户服务接口实现，关键词：{}", keyword);
            return new ArrayList<>();
        } catch (Exception e) {
            log.error("搜索用户失败，关键词：{}", keyword, e);
            return new ArrayList<>();
        }
    }

    /**
     * 获取已关联的用户ID列表
     */
    private List<Long> getAssociatedUserIds(Long propertyCompanyId) {
        if (propertyCompanyId == null) {
            return new ArrayList<>();
        }

        try {
            LambdaQueryWrapper<UserPropertyCompany> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserPropertyCompany::getPropertyCompanyId, propertyCompanyId);
            List<UserPropertyCompany> associatedUsers = this.list(queryWrapper);
            
            return associatedUsers.stream()
                    .map(UserPropertyCompany::getUserId)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取已关联用户ID列表失败，物业公司ID：{}", propertyCompanyId, e);
            return new ArrayList<>();
        }
    }

    /**
     * 创建用户物业公司关联记录
     */
    private UserPropertyCompany createUserPropertyCompany(Long propertyCompanyId, AddEmployeeDTO addEmployeeDTO) {
        UserPropertyCompany userPropertyCompany = new UserPropertyCompany();
        userPropertyCompany.setUserId(addEmployeeDTO.getUserId());
        userPropertyCompany.setPropertyCompanyId(propertyCompanyId);
        userPropertyCompany.setPosition(addEmployeeDTO.getPosition());
        userPropertyCompany.setDepartment(addEmployeeDTO.getDepartment());
        userPropertyCompany.setEmployeeNo(addEmployeeDTO.getEmployeeNo());
        userPropertyCompany.setJoinDate(addEmployeeDTO.getJoinDate());
        userPropertyCompany.setStatus(SystemStatusEnum.ENABLED.getCode()); // 使用SystemStatusEnum
        userPropertyCompany.setRemark(addEmployeeDTO.getRemark());
        userPropertyCompany.setCreateBy(SecurityUtils.getCurrentUserId());
        userPropertyCompany.setCreateTime(LocalDateTime.now());
        userPropertyCompany.setUpdateBy(SecurityUtils.getCurrentUserId());
        userPropertyCompany.setUpdateTime(LocalDateTime.now());
        
        return userPropertyCompany;
    }

    /**
     * 更新用户物业公司关联记录字段
     */
    private void updateUserPropertyCompanyFields(UserPropertyCompany userPropertyCompany, UpdateEmployeeDTO updateEmployeeDTO) {
        if (StringUtils.isNotBlank(updateEmployeeDTO.getPosition())) {
            userPropertyCompany.setPosition(updateEmployeeDTO.getPosition());
        }
        if (StringUtils.isNotBlank(updateEmployeeDTO.getDepartment())) {
            userPropertyCompany.setDepartment(updateEmployeeDTO.getDepartment());
        }
        if (StringUtils.isNotBlank(updateEmployeeDTO.getEmployeeNo())) {
            userPropertyCompany.setEmployeeNo(updateEmployeeDTO.getEmployeeNo());
        }
        if (updateEmployeeDTO.getJoinDate() != null) {
            userPropertyCompany.setJoinDate(updateEmployeeDTO.getJoinDate());
        }
        if (updateEmployeeDTO.getStatus() != null) {
            userPropertyCompany.setStatus(updateEmployeeDTO.getStatus());
        }
        if (StringUtils.isNotBlank(updateEmployeeDTO.getRemark())) {
            userPropertyCompany.setRemark(updateEmployeeDTO.getRemark());
        }
    }

    /**
     * 转换为EmployeeVO
     */
    private EmployeeVO convertToEmployeeVO(UserPropertyCompany userPropertyCompany, UserDTO userDTO) {
        EmployeeVO employeeVO = new EmployeeVO();
        BeanUtils.copyProperties(userPropertyCompany, employeeVO);

        // 设置用户信息
        if (userDTO != null) {
            employeeVO.setUsername(userDTO.getUsername());
            employeeVO.setRealName(userDTO.getRealName());
            employeeVO.setPhone(userDTO.getPhone());
            employeeVO.setEmail(userDTO.getEmail());
        } else {
            // 如果用户信息获取失败，设置默认值
            employeeVO.setUsername("用户" + userPropertyCompany.getUserId());
            employeeVO.setRealName("用户" + userPropertyCompany.getUserId());
            employeeVO.setPhone("");
            employeeVO.setEmail("");
        }

        // 设置状态名称
        employeeVO.setStatusName(getStatusName(userPropertyCompany.getStatus()));

        return employeeVO;
    }

    /**
     * 转换为UserVO
     */
    private UserVO convertToUserVO(UserDTO userDTO) {
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userDTO, userVO);
        return userVO;
    }

    /**
     * 获取状态名称
     * 使用SystemStatusEnum统一状态管理
     */
    private String getStatusName(Integer status) {
        if (status == null) return "";
        
        SystemStatusEnum statusEnum = SystemStatusEnum.getByCode(status);
        if (statusEnum != null) {
            return statusEnum.getDescription();
        }
        
        // 兼容旧的状态值
        switch (status) {
            case 0: return "离职";
            case 1: return "在职";
            case 2: return "待入职";
            default: return "未知";
        }
    }

    /**
     * 验证用户对物业公司的数据权限
     * 严格按照《DataScopeFeign使用示例.md》规范实现
     */
    private void validatePropertyCompanyPermission(Long propertyCompanyId) throws Exception {
        if (propertyCompanyId == null) {
            throw new BusinessException("物业公司ID不能为空");
        }

        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            if (currentUserId == null) {
                throw new BusinessException("用户未登录");
            }

            // 使用DataScopeService检查权限
            try {
                boolean hasPermission = dataScopeService.hasPropertyCompanyPermission(currentUserId, propertyCompanyId);
                if (!hasPermission) {
                    throw new BusinessException("您没有权限访问该物业公司的数据");
                }
            } catch (Exception e) {
                log.error("检查用户物业公司权限失败，用户ID：{}，物业公司ID：{}", currentUserId, propertyCompanyId, e);
                throw new BusinessException("权限验证失败：" + e.getMessage());
            }

            log.debug("用户{}对物业公司{}的权限验证通过", currentUserId, propertyCompanyId);

        } catch (Exception e) {
            log.error("数据权限验证失败，用户ID：{}，物业公司ID：{}", SecurityUtils.getCurrentUserId(), propertyCompanyId, e);
            if (e instanceof BusinessException) {
                throw e;
            }
            throw new BusinessException("数据权限验证失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前用户的数据权限信息
     * 用于缓存和性能优化
     */
    @Cacheable(value = "permission", key = "'data_scope:' + #userId", unless = "#result == null")
    private DataScopeInfo getCurrentUserDataScope(Long userId) {
        try {
            return dataScopeService.getUserDataScope(userId);
        } catch (Exception e) {
            log.error("获取用户数据权限信息失败，用户ID：{}", userId, e);
            return null;
        }
    }
} 
